from rest_framework.views import APIView
from app.account.models import UserInfo, UserLog
from app.log.models import LoginLog
from common.authCheck.userAuth import check_login, getUser
from django.db.models import Q
from django.http import JsonResponse
import json


class AccountBaseInfoView(APIView):

    def get(self, request):
        """
        获取登录信息
        :param request:
        :return:
        """
        if request.session.get('login') is not None:
            user = getUser(request.session.get('login'))
            return JsonResponse({
                'status': True,
                'id': user.id,
                'nickname': user.nickname
            })
        else:
            return JsonResponse({
                'status': False,
                'errMsg': '你还未登录'
            }, status=401)

    def post(self, request):
        """
        用户登录
        :param request:
        :return:
        """
        try:
            jsonParams = json.loads(request.body.decode('utf-8'))
            user = UserInfo.objects.filter(
                Q(email=jsonParams.get('email', '')) |
                Q(nickname=jsonParams.get('nickname', ''))
            )
            if not user.exists():
                return JsonResponse({
                    'status': False,
                    'errMsg': '账户不存在'
                }, status=404)
            user = user[0]
            if user.user_role == '6':
                return JsonResponse({
                    'status': False,
                    'errMsg': '用户已被封禁'
                }, status=401)
            db_password = user.password.password
            from django.contrib.auth.hashers import check_password
            if check_password(jsonParams.get('password'), db_password):
                # 在session中记录
                request.session['login'] = user.email
                from django.utils.timezone import now
                UserLog.objects.get(related_user=user).last_login_time = now
                LoginLog.objects.create(
                    ip=request.META['REMOTE_ADDR'],
                    user=user,
                    login_device=jsonParams.get('device')
                )
                return JsonResponse({
                    'status': True,
                    'id': user.id,
                    'email': user.email,
                    'nickname': user.nickname
                })
            else:
                return JsonResponse({
                    'status': False,
                    'errMsg': '密码错误'
                }, status=403)

        except Exception as ex:
            return JsonResponse({
                'status': False,
                'errMsg': str(ex)
            })

    @check_login
    def delete(self, request):
        """
        登出账户
        :param request:
        :return:
        """
        user = getUser(request.session.get('login'))
        # 删除服务器session
        request.session['login'] = None
        return JsonResponse({
            'status': True,
            'id': user.id
        })
